/**
 * 
 */
package com.alipay.test.dbtest;

import java.io.IOException;
import java.util.Properties;

import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.operation.DatabaseOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.test.dbtest.operation.ScriptDatabaseOperation;

/**
 * @author quickpoint
 * 
 */
public abstract class ScriptableDatabaseTestCase extends DBTestCase {

    private static final Logger logger                 = LoggerFactory
                                                           .getLogger(ScriptableDatabaseTestCase.class);

    public static final String  DB_TEST_PROP           = "dbtest.properties";
    public static final String  DB_TEST_DRIVER_CLASS   = "dbtest.driverClass";
    public static final String  DB_TEST_CONNECTION_URL = "dbtest.conntionUrl";
    public static final String  DB_TEST_SCHEMA         = "dbtest.schema";
    public static final String  DB_TEST_USERNAME       = "dbtest.username";
    public static final String  DB_TEST_PASSWORD       = "dbtest.password";

    protected abstract String[] configSetUpScript();

    protected abstract String[] configTearDownScript();

    public ScriptableDatabaseTestCase() {
        loadDatabaseProperties();
    }

    private void loadDatabaseProperties() {
        try {
            Properties prop = new Properties();
            prop.load(this.getClass().getClassLoader().getResourceAsStream(DB_TEST_PROP));
            System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, prop
                .getProperty(DB_TEST_DRIVER_CLASS));
            System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, prop
                .getProperty(DB_TEST_CONNECTION_URL));
            System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, prop
                .getProperty(DB_TEST_SCHEMA));
            System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, prop
                .getProperty(DB_TEST_USERNAME));
            System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, prop
                .getProperty(DB_TEST_PASSWORD));

        } catch (IOException ex) {
            logger.error("Failed to load dbtest.properties", ex);
        }
    }

    @Override
    protected DatabaseOperation getSetUpOperation() throws Exception {
        return new ScriptDatabaseOperation(configSetUpScript());
    }

    @Override
    protected DatabaseOperation getTearDownOperation() throws Exception {
        return new ScriptDatabaseOperation(configTearDownScript());
    }

}
